Getting Started with the uWebKit3 Beta

Introduction

uWebKit is a high performance WebView plugin for Unity that has been available since 2011. uWebKit3 is now powered by Google Chromium and provides the latest in web standards. uWebKit includes full C# source for the Unity API with native C++ source code available under the uWebKit Pro Source License.

Technical Requirements

Table of Contents

1) Running the Browser Example
2) UWKWebView Component
3) Global JavaScript Properties
4) Evaluating JavaScript
5) Calling Unity from JavaScript with WebQueries
6) Dynamically adding a WebView
7) Basic UWKWebView API
8) UWKWebView Delegates
9) Known Issues and Reporting Issues
10) Coming Soon

Running the Browser Example

The uWebKit3 Beta zip file contains the Unity package and this getting started documentation.

The Unity package will import cleanly into any Unity 5 project adding uWebKit and uWebKitExamples folders. Open the Example1WebBrowser scene located in the uWebKitExamples/Scenes folder and press play.

The uWebKit3 Beta package expires and will display a reminder the first time a scene is played in the editor. The beta also renders a watermark at regular intervals. If expired, please check http://www.uwebkit.com for beta updates.

The simple Browser example features multiple tabs, an address bar, and bookmarks.

UWKWebView Component

The UWKWebView component renders a Chromium WebView to a Unity Texture2D. It provides API for user interaction with the web page. It also supports JavaScript evaluation, global properties, and calling into Unity from the web page using WebQueries.

It is important to note that the UWKWebView component encapsulates a web page though doesn't define how it is displayed. In order to display a page, please see the WebGUI and WebTexture example scenes.

Inspector Fields

Inspector Fields

There are a few basic properties which can be set in the inspector for a UWKWebView.

Property Description
URL The initial URL to load at WebView creation
Initial Width The initial width of the web page
Initial Height The initial height of the web page
Max Width The maximum width of any web page
Max Height The maximum height of any web page
Scroll Sensitivity Multiplier for scroll speed of web page
Web Texture Useful for inspecting the web texture at runtime

2D WebView Example

The Example2WebGUI scene demonstrates using the WebGUI example script to render and interact with a web page using Unity's GUI system.

3D WebView Example

The Example4Scene scene demonstrates using the WebTexture example script to render and interact with a web page in 3D.

Global JavaScript Properties

From Unity it is possible to set global property objects that the web page can access, even at page load time. This is done by using the static UWKWebView method SetGlobalProperty. Properties are read-only on the page's JavaScript side. In order to communicate with Unity from the web page, use a WebQuery which is described below.

// Example of setting up a global Unity object with a
// unityVersion property that is accessible in JavaScript
UWKWebView.SetGlobalProperty ("Unity", "unityVersion", Application.unityVersion);

In JavaScript, it is easy to access the global property:

// Output the version of Unity we're running
console.log(Unity.unityVersion);

Evaluating JavaScript

JavaScript can be evaluated on the page with an asynchronous return value:


// Example of retrieving the web page title using JS evaluation
view.EvaluateJavascript("document.title;", (success, value) => {
    if (success)
      Debug.Log("JSEval Result: Title = " + value);
    else
      Debug.Log("Error: " + value);    
});

JavaScript can also be executed on the page discarding any return value for performance benefits:


// Example of changing the web page title
view.ExecuteJavascript("document.title = \"Hello from uWebKit3!\";");

Calling Unity from JavaScript with WebQueries

It is possible to call Unity code from the web view using a WebQuery. On the window object, uWebKit adds an "uwkQuery" function which takes an object that has a request string and success/failure callbacks:

// call window.uwkQuery to query the UWKWebView C# component
// in Unity from the web page

window.uwkQuery({
    // request string, will be passed to Unity
    request: requestString,
    // success callback
    onSuccess: function(response) {
      console.log(response)
    },
    // failure callback
    onFailure: function(error_code, error_message) {
      console.log("Error: ", error_code, error_message);
    }
});  

Using window.uwkQuery, we can construct a simple message type + data protocol, for example:


// simple messageCount counter
var messageCount = 0;

// encode a message type and message JSON into a Unity request
function sendWebQuery(msgType, msgJSON) {

      const data = {
          message: msgType,
          payload: msgJSON
      };

      window.uwkQuery({
          // encode the request as a JSON string
          request: JSON.stringify(data),
          onSuccess: function(response) {
            console.log("Message Count: " + response); }
          }
      });
  }

We'll wire up a button on the page that will pass the web query to Unity:

<input type='button' value="Bump Count" onclick='sendWebQuery("UnityMessage", { "messageCount: ++messageCount})' /><br>

On the Unity side of things, we need to setup a WebQuery delegate on our view:


// Web Query Class
public class UWKWebQuery
{
  // The web view this query was executed on
  public UWKWebView View;
  // unique identifier of the query
  public double QueryID;
  // The string request generated in page JavaScript
  public string Request;

  // Callback from Unity -> web page for success
  public void Success(string result);
  // Callback from Unity -> web page for error
  public void Failure(int errCode, string result);
}

// Example web query callback
void onWebQuery(UWKWebQuery query)
{
  // We defined our query protocol to use JSON
  // in the sendWebQuery JavaScript function, so we can deserialize it thus
  var request = UWKJson.Deserialize(query.Request) as Dictionary<string, object>;

  // Get the message type, again encoded in the sendWebQuery JS function
  var message = request["message"] as string;

  if (message == "UnityMessage")
  {
      // Get the messageCount from the payload
      var payload = request["payload"] as Dictionary<string, object>;
      var messageCount = (long)payload["messageCount"];

      // Now return a string result back to the web page via the success callback!
      query.Success("Query Response from Unity: Message Count = " + messageCount);
  }
}

All that's left is to hook the web query delegate up to our view:

view.WebQuery += onWebQuery;

Dynamically adding a WebView

When creating UWKWebView components procedurally, the static UWKWebView.AddToGameObject method provides convenience in specifying arguments for properties:


// Dynamically adds a UWKWebView component to a GameObject with initialization
public static UWKWebView AddToGameObject(GameObject gameObject, string url = "",
                                         int initialWidth = 1024, int initialHeight = 1024,
                                         int maxWidth = 1024, int maxHeight = 1024)  

Basic UWKWebView API

The UWKWebView component renders a web page to a Unity Texture2D suitable for use in 2D UI and 3D scenes. The full C# source code to the component script is included and recommended for implementation and specific usage details.


// Core WebView class
public class UWKWebView : MonoBehaviour
{

  // Navigate the view to the specified URL (http://, file://, etc)
  public void LoadURL(string url);

  // Load the HTML string into web view using specified url scheme
  public void LoadHTML(string html, string url = "http://localcontent/");

  // Execute Javascript on the page discarding any return value as an optimization
  public void ExecuteJavascript(string javascript);

  // Evaluates Javascript on the page with return value
  public void EvaluateJavascript(string javascript, JSEvalDelegate callback = null);

  // Process the mouse given mousePos coordinates
  public void ProcessMouse(Vector3 mousePos);

  // Process a Unity keyboard event
  public void ProcessKeyboard(Event keyEvent);

  // Moves forward in the page history
  public void Forward();

  // Moves back in the page history
  public void Back();

  // Navigation for going backwards and forwards through the UWKWebView's history
  // view's current height to be equal or smaller than this value
  public enum Navigation
  {
      Forward = 0,
      Back
  }

  // Navigates forward or back in the page history
  public void Navigate(Navigation n);

  // Sets a global property that is readable from page JavaScript, including during load
  public static void SetGlobalProperty(string globalVarName, string propertyName, object value);

  // Convenience to draw the web texture using Unity GUI
  public void DrawTexture(Rect position, bool alphaBlend = true);

}

UWKWebView Delegates

The UWKWebView component features several delegates for handling WebView events

// JSEvalDelegate - Event fired when return value of some evaluated Javascript is returned
public delegate void JSEvalDelegate(bool success, string value);

// URLChangedDelegate - Event fired when the URL has been changed
// either by user input or due to a page redirect
public delegate void URLChangedDelegate(UWKWebView view, string url);

// TitleChangedDelegate - Event fired when the title of a web page has changed
public delegate void TitleChangedDelegate(UWKWebView view, string title);

// LoadFinishedDelegate - Event fired once the page has been fully loaded
public delegate void LoadFinishedDelegate(UWKWebView view);

// LoadStateChangedDelegate
public delegate void LoadStateChangedDelegate(UWKWebView view, bool loading, bool canGoBack, bool canGoForward);

// PopupRequestDelegate - Event fired if the page requests a popup window
public delegate void PopupRequestDelegate(UWKWebView view, string url);

// UWKWebQueryDelegate - Event fired when receiving a web query from a web page
public delegate void UWKWebQueryDelegate(UWKWebQuery query);  

Known Issues and Reporting Issues

Known Issues
Reporting Issues

Coming Soon

uWebKit is (c) 2011-2016 THUNDERBEAST GAMES LLC